Page({
    data: {
        // 个人信息
        personalInfo: {
            name: '',
            phone: '',
            email: '',
            jobIntention: ''
        },

        // 教育经历
        educations: [{
            school: '',
            major: '',
            startDate: '',
            endDate: ''
        }],

        // 工作经历
        works: [{
            company: '',
            position: '',
            startDate: '',
            endDate: '',
            description: ''
        }],

        // 技能证书
        skills: [{
            name: '',
            level: 50,
        }],

        // 项目经验
        projects: [{
            name: '',
            period: '',
            responsibility: '',
            achievement: ''
        }]
    },

    // 个人信息输入
    onPersonalInfoInput(e) {
        const { field } = e.currentTarget.dataset;
        this.setData({
            [`personalInfo.${field}`]: e.detail.value
        });
    },

    // 教育经历输入
    onEducationInput(e) {
        const { index, field } = e.currentTarget.dataset;
        this.setData({
            [`educations[${index}].${field}`]: e.detail.value
        });
    },

    // 工作经历输入
    onWorkInput(e) {
        const { index, field } = e.currentTarget.dataset;
        this.setData({
            [`works[${index}].${field}`]: e.detail.value
        });
    },

    // 技能证书输入
    onSkillInput(e) {
        const { index, field } = e.currentTarget.dataset;
        this.setData({
            [`skills[${index}].${field}`]: e.detail.value
        });
    },

    // 项目经验输入
    onProjectInput(e) {
        const { index, field } = e.currentTarget.dataset;
        this.setData({
            [`projects[${index}].${field}`]: e.detail.value
        });
    },

    // 添加教育经历
    addEducation() {
        this.setData({
            educations: [...this.data.educations, {
                school: '',
                major: '',
                startDate: '',
                endDate: ''
            }]
        });
    },

    // 删除教育经历
    removeEducation(e) {
        const { index } = e.currentTarget.dataset;
        const educations = this.data.educations.filter((_, i) => i !== index);
        this.setData({ educations });
    },

    // 添加工作经历
    addWork() {
        this.setData({
            works: [...this.data.works, {
                company: '',
                position: '',
                startDate: '',
                endDate: '',
                description: ''
            }]
        });
    },

    // 删除工作经历
    removeWork(e) {
        const { index } = e.currentTarget.dataset;
        const works = this.data.works.filter((_, i) => i !== index);
        this.setData({ works });
    },

    // 添加技能证书
    addSkill() {
        this.setData({
            skills: [...this.data.skills, {
                name: '',
                level: 50,
            }]
        });
    },

    // 删除技能证书
    removeSkill(e) {
        const { index } = e.currentTarget.dataset;
        const skills = this.data.skills.filter((_, i) => i !== index);
        this.setData({ skills });
    },

    // 添加项目经验
    addProject() {
        this.setData({
            projects: [...this.data.projects, {
                name: '',
                period: '',
                responsibility: '',
                achievement: ''
            }]
        });
    },

    // 删除项目经验
    removeProject(e) {
        const { index } = e.currentTarget.dataset;
        const projects = this.data.projects.filter((_, i) => i !== index);
        this.setData({ projects });
    },

    // 技能熟练度变化
    onSkillLevelChange(e) {
        const { index } = e.currentTarget.dataset;
        this.setData({
            [`skills[${index}].level`]: e.detail.value
        });
    },

    // 日期选择
    onDatePickerChange(e) {
        const { type, index, field } = e.currentTarget.dataset;
        this.setData({
            [`${type}[${index}].${field}`]: e.detail.value
        });
    },

    // 预览简历
    previewResume(e) {
        const { type } = e.currentTarget.dataset;
        wx.cloud.callFunction({
            name: 'getAllResumes',
            success: res => {
                const resumes = res.result.data.filter(item => item.enable !== false);
                const names = resumes.map(item => item.name);
                wx.showActionSheet({
                    itemList: names,
                    success: res => {
                        const selectedResume = resumes[res.tapIndex];
                        const resumeTemplate = {
                            personalInfo: [this.data.personalInfo],
                            educations: this.data.educations,
                            projects: this.data.projects,
                            skills: this.data.skills,
                            works: this.data.works
                        }
                        // 调用设置简历模板云函数
                        wx.cloud.callFunction({
                            name: 'setResumeTemplate',
                            data: {
                                templateUrl: selectedResume.fileid,
                                complexData: resumeTemplate
                            },
                            success: (res) => {
                                console.log('设置模板成功', res);
                                if (res.result.success) {
                                    wx.showToast({
                                        title: '模板设置成功',
                                        icon: 'success'
                                    });

                                    // -----------------------------
                                    try {
                                        const fileID = res.result.fileID
                                        if (!fileID) {
                                            throw new Error('模板ID不存在');
                                        }
                                        if (type == "preview") {
                                            this.openDocument(fileID);

                                        } else {
                                            this.copyTemplateLink(fileID)
                                        }

                                    } catch (err) {
                                        console.error('跳转出错:', err);
                                        wx.showToast({
                                            title: err.message || '跳转出错',
                                            icon: 'none'
                                        });
                                    }

                                    // ------------------- ------------------

                                } else {
                                    wx.showToast({
                                        title: '模板设置失败',
                                        icon: 'none'
                                    });
                                }

                            },
                            fail: err => {
                                wx.showToast({
                                    title: '模板设置失败',
                                    icon: 'none'
                                });
                                console.error('设置模板失败', err);
                            }
                        });
                    },
                    fail: err => {
                        console.log('用户取消选择', err);
                    }
                });
            },
            fail: err => {
                wx.showToast({
                    title: '获取简历失败',
                    icon: 'none'
                });
                console.error('调用云函数失败', err);
            }
        });
    },

    // 打开文档
    openDocument(fileidPdf) {
        let that = this;
        if (!fileidPdf) {
            this.handleError('缺少模板ID参数');
            return;
        }
        wx.showModal({
            title: '提示',
            content: 'Word预览模式，手机端可能错乱，建议复制链接下载查看',
            cancelText: "取消预览",
            confirmText: "继续预览",
            success(res) {
                if (res.confirm) {
                    // 显示文档转换提示
                    wx.showLoading({
                        title: '文档转换中',
                        mask: true
                    });
                    that.getTempFileURL(fileidPdf)
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })




    },


    // 获取临时文件链接, 并打开文件
    getTempFileURL(fileidPdf) {
        if (!fileidPdf) {
            wx.hideLoading();
            console.error('缺少文件fileidPdf');
            return;
        }

        // 获取临时文件链接
        wx.cloud.getTempFileURL({
            fileList: [fileidPdf]
        }).then(res => {
            const fileInfo = res.fileList[0];
            if (fileInfo.tempFileURL) {
                const tempFileURL = fileInfo.tempFileURL;

                // 下载文件并打开
                wx.downloadFile({
                    url: tempFileURL,
                    success: function (res) {
                        const filePath = res.tempFilePath;
                        if (filePath) {
                            wx.openDocument({
                                filePath: filePath,
                                fileType: 'docx',
                                success: function (res) {
                                    wx.hideLoading();
                                    console.log('打开文档成功');
                                },
                                fail: function (err) {
                                    wx.hideLoading();
                                    console.error('打开文档失败', err);
                                }
                            });
                        } else {
                            wx.hideLoading();
                            console.error('文件路径无效');
                        }
                    },
                    fail: function (err) {
                        wx.hideLoading();
                        console.error('下载失败', err);
                    }
                });
            } else {
                wx.hideLoading();
                console.error('获取临时链接失败', fileInfo);
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('获取临时文件链接失败:', err);
        });


    },
    // 复制模板链接
    copyTemplateLink(fileid) {


        if (!fileid) {
            wx.showToast({
                title: '模板文件不存在',
                icon: 'none'
            })
            return
        }

        wx.showLoading({
            title: '获取下载链接中...',
            mask: true
        })

        wx.cloud.callFunction({
            name: 'getResumeUrl',
            data: { fileID: fileid },
            success(res) {
                if (res.result.code === 0) {
                    const url = res.result.data.url
                    wx.setClipboardData({
                        data: url,
                        success: () => {
                            wx.showModal({
                                title: '复制成功',
                                content: `下载链接已复制到剪贴板\n\n链接2分钟后失效，请及时下载\n\n文件名: ${template.title}.${fileType}`,
                                showCancel: false,
                                confirmText: '知道了'
                            })
                        },
                        fail: (err) => {
                            wx.showToast({
                                title: '复制失败: ' + (err.errMsg || '未知错误'),
                                icon: 'none'
                            })
                        }
                    })
                } else {
                    wx.showToast({
                        title: res.result.message || '获取下载链接失败',
                        icon: 'none'
                    })
                }
            },
            fail(err) {
                wx.showToast({
                    title: '获取下载链接失败',
                    icon: 'none'
                })
                console.error(err)
            },
            complete() {
                wx.hideLoading()
            }
        })

    },

});